package history.hot100;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

// 102. 二叉树的层序遍历:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
// 题解：https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/bfs-de-shi-yong-chang-jing-zong-jie-ceng-xu-bian-l/
public class LeetCode_102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();

        ArrayDeque<TreeNode> queue = new ArrayDeque();
        if (root != null) queue.add(root);

        while (!queue.isEmpty()) {
            int n = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                TreeNode treeNode = queue.poll();
                level.add(treeNode.val);
                if (treeNode.left!=null) {
                    queue.add(treeNode.left);
                }
                if (treeNode.right!=null) {
                    queue.add(treeNode.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }
}
